import { ref } from "vue";
import { getPostList, getSearchList } from "@/api/index";

export default function usePostSearch() {
  let pageParams = ref({
    loading: false,
    finished: false,
    error: false,
    page: 1,
    pageSize: 10,
    finishedText: "没有更多了",
  });
  let postList = ref([]);
  let localParams = {};
  let url = getPostList; //默认是最新发布的接口
  const searchPostList = (data) => {
    if (data) {
      postList.value = [];
      pageParams.value.page = 1;
      pageParams.value.finished = false;
      localParams = Object.assign(localParams, data);
      url = getSearchList;
      console.log("localParams", localParams);
    }
    let params = {
      area: localParams.area,
      edu: localParams.edu,
      xz: localParams.cxz,
      flag_type: 8,
      yuangong: localParams.yuangong,
      keywords: localParams.keywords,
      classid: localParams.classid,
      regionid: localParams.regionid,
      gznum: localParams.gznum,
      salary: localParams.salary,
      page: pageParams.value.page - 1,
      page_size: localParams.pageSize || pageParams.value.pageSize,
    };
    pageParams.value.loading = true;

    url(params)
      .then((res) => {
        if (res.code == 200) {
          // 修改这里 - 如果是第一页则替换，否则追加
          if (params.page === 0) {
            // 第一页
            postList.value = res.data;
          } else {
            postList.value.push(...res.data);
          }
          if (!res.data.length && pageParams.value.page == 1) {
            pageParams.value.finishedText = "很抱歉，未找到符合要求的信息！";
          } else {
            pageParams.value.finishedText = "没有更多了";
          }
          if (res.data.length < pageParams.value.pageSize) {
            pageParams.value.finished = true;
          }
          if (!pageParams.value.finished) {
            pageParams.value.page++;
          }
        } else {
          pageParams.value.error = true;
        }
        pageParams.value.loading = false;
      })
      .catch((err) => {
        pageParams.value.error = true;
        pageParams.value.loading = false;
      });
  };

  return {
    pageParams,
    postList,
    searchPostList,
  };
}
